<script setup lang="ts">
import {ref, nextTick, defineExpose, getCurrentInstance} from 'vue'
import type {TabsPaneContext, ElTabs} from 'element-plus'
import {Back} from "@element-plus/icons-vue";
import {useRouter, useRoute} from "vue-router";

const activeName = ref('zero')
const tabsRef = ref<InstanceType<typeof ElTabs>>() // 绑定Tabs组件

// useRoute: 取路由参数
// useRouter: 1.编程式路由跳转，2.还有<router-link>方式

const router = useRouter();
const route = useRoute(); //路由参数(query/params) 包含在 route 对象中
const {query} = useRoute();

//编程式路由跳转
const testRouter = () => {
  router.go(-1) // history.back(), history.forward(), history.go(-1|1)
  // router.back()  //后退历史
  // router.forward(); //前进历史
}

// 存储所有演出信息
const performancesList = ref<Array<{
  pid: number;
  pname: string;
  rurl: string;
  purl: string;
  pdetail: string;
  pprice: string;
  ptime: string;
  plocation: string;
  performanceType: number;
  recommendType: number;
}>>([]);

// 标签名与后端类型的映射关系
const typeMap = {
  zero: 0,      // 全部
  first: 1,     // 演唱会
  second: 2,    // 脱口秀
  third: 3,     // 休闲展览
  fourth: 4,    // 话剧音乐剧
  fifth: 5,     // 音乐节
  sixth: 6,     // 亲子艺术
  seventh: 7,   // 音乐会
  eighth: 8     // 相声
}

const global = getCurrentInstance().appContext.config.globalProperties;

// 封装获取演出数据的函数
const fetchPerformances = (type: number) => {
  if (type > 0) {
    global.$http.get(`/public/maoyanmovieproject/queryPerformanceByType/${type}`)
        .then(resp => {
          console.log(resp.data);
          performancesList.value = resp.data;
        })
        .catch(err => {
          console.error('获取演出数据失败:', err);
        })
  } else {
    global.$http.get('/public/maoyanmovieproject/queryAllPerformance')
        .then(resp => {
          console.log(resp.data);
          performancesList.value = resp.data;
        })
        .catch(err => {
          console.error('获取演出数据失败:', err);
        })
  }

}

// 初始化时加载默认数据（全部类型）
fetchPerformances(typeMap.zero);

const handleClick = async (tab: TabsPaneContext, event: Event) => {
  // 获取当前选中标签对应的类型值
  const currentType = typeMap[tab.paneName as keyof typeof typeMap];
  // 调用接口获取对应类型的数据
  fetchPerformances(currentType);

  await nextTick() // 等待DOM更新

  // 滚动逻辑保持不变
  const navWrap = tabsRef.value?.$el.querySelector('.el-tabs__nav') as HTMLElement | null
  if (!navWrap) return

  const activeTab = navWrap.querySelector('.el-tab.is-active') as HTMLElement | null
  if (!activeTab) return

  const containerWidth = navWrap.offsetWidth
  const tabLeft = activeTab.offsetLeft
  const tabWidth = activeTab.offsetWidth
  const maxScrollLeft = navWrap.scrollWidth - containerWidth

  let targetScrollLeft = tabLeft - (containerWidth / 2) + (tabWidth / 2)
  targetScrollLeft = Math.max(0, Math.min(targetScrollLeft, maxScrollLeft))

  navWrap.scrollTo({
    left: targetScrollLeft,
    behavior: 'smooth'
  })
}
</script>

<template>

  <!-- 顶部搜索框和返回按钮 -->
  <div class="CategoryNavigationBar">
    <br>
    <!-- 返回图标-->
    <el-row class="header" align="middle">
      <el-col :span="6" align="center">
        <el-icon class="header-back" @click="testRouter">
          <ArrowLeft/>
        </el-icon>
      </el-col>
      <el-col :span="18">
        <div class="myList">
          <h3>演出列表</h3>
        </div>
      </el-col>
    </el-row>
    <br>

    <!--第二栏搜索框-->
    <el-row class="header" align="middle">

      <el-col :span="6">
        <div class="header-city">
          桂林
          <el-icon style="font-size: 20px;">
            <CaretBottom/>
          </el-icon>
        </div>
      </el-col>

      <el-col :span="18">
        <div class="header-search">

          <!--  点击搜索框跳转到搜索页面        -->
          <router-link :to="{path: '/performance-search'}">
            <el-input
                v-model="searchQuery"
                placeholder="找明星/演出/场馆"
                class="search-input"
                :prefix-icon="Search"
                @focus="showResults = !!searchQuery.trim()"
            />
          </router-link>

        </div>
      </el-col>

    </el-row>
    <br>


    <!-- 给el-tabs添加ref，用于获取DOM -->
    <el-tabs ref="tabsRef" v-model="activeName" class="navigation_bar" @tab-click="handleClick">
      <el-tab-pane label="全部" name="zero"></el-tab-pane>
      <el-tab-pane label="演唱会" name="first"></el-tab-pane>
      <el-tab-pane label="脱口秀" name="second"></el-tab-pane>
      <el-tab-pane label="休闲展览" name="third"></el-tab-pane>
      <el-tab-pane label="话剧音乐剧" name="fourth"></el-tab-pane>
      <el-tab-pane label="音乐节" name="fifth"></el-tab-pane>
      <el-tab-pane label="亲子艺术" name="sixth"></el-tab-pane>
      <el-tab-pane label="音乐会" name="seventh"></el-tab-pane>
      <el-tab-pane label="相声" name="eighth"></el-tab-pane>
    </el-tabs>


    <!-- 页面展示内容 -->
    <el-row v-for="item in performancesList" :key="item.pid">
      <el-col :span="6">
        <!-- 路由链接 -->
        <router-link :to="{path: '/performance-detail', query: { id: item.pid }}" tag="div">
          <el-image :src="item.purl"></el-image>
        </router-link>
      </el-col>
      <el-col :span="18">
        <el-row>
          <el-col :span="24">
            <router-link :to="{path: '/performance-detail', query: { id: item.pid }}" tag="div" class="link">
              {{ item.pname }}
            </router-link>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div> {{ item.ptime }}</div>
            <div>{{ item.plocation }}</div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" class="recommend-item-price">
            <div class="item-price">￥{{ item.pprice }}起</div>
          </el-col>
        </el-row>
      </el-col>
    </el-row>

  </div>
</template>

<style scoped>
.navigation_bar {
  /* 确保导航栏可横向滚动 */

  .el-tabs__nav-wrap {
    overflow-x: auto;
    scrollbar-width: none;
  }

  .el-tabs__nav-wrap::-webkit-scrollbar {
    display: none;
  }

  .el-tabs__nav {
    white-space: nowrap;
  }

  > .el-tabs__content {
    padding: 32px;
    color: #6b778c;
    font-size: 32px;
    font-weight: 600;
  }
}

/*填充*/
.CategoryNavigationBar {
  padding: 10px 10px;
}

/*填充 城市名*/
.header-city {
  padding-left: 10px;
}

/*搜索框*/
/*.header-search {
  display: flex;
  align-items: center;
  width: 100%;
  height: 38px;
  border-radius: 8px;
  background: #f2f2f2;
  padding-right: 10px;
}*/
.search-input {
  width: 100%;
  max-width: 600px;
}
.myList{
  padding-left: 50px;
}
.link{
  text-decoration: none;
}
</style>
